package com.jugheadzhou.auth.endpoint;

import com.jugheadzhou.auth.core.websocket.WebSocketManager;
import com.jugheadzhou.auth.core.websocket.config.GetHttpSessionConfigurator;
import com.jugheadzhou.auth.service.UserService;
import com.jugheadzhou.auth.util.SpringUtils;
import org.apache.tomcat.websocket.WsSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * WebSocket定义
 *
 * @author jugheadzhou
 */
@Component
@ServerEndpoint(value = "/websocket/connect/{connectionId}", configurator = GetHttpSessionConfigurator.class)
public class WebSocketEndpoint {
    private static final Logger log = LoggerFactory.getLogger(WebSocketEndpoint.class);
    private static final String CONNECTION_ID = "connectionId";
    private WebSocketManager webSocketManager = SpringUtils.getBean(WebSocketManager.class);
    private UserService userService = SpringUtils.getBean(UserService.class);

    @OnOpen
    public void onOpen(Session session, @PathParam(CONNECTION_ID) String connectionId) {
        log.info("WebSocket opened from sessionId " + ((WsSession) session).getHttpSessionId() + " , connectionId = " + connectionId);
        // TODO 当connectionId重复时需要提醒
        webSocketManager.connect(connectionId, session);
        // TODO 建立连接时查询初始数据
        webSocketManager.sendMessage(connectionId, userService.selectScoreByWsConnectionId(connectionId));
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam(CONNECTION_ID) String connectionId) {
        log.info("WebSocket received " + message + " from sessionId " + ((WsSession) session).getHttpSessionId() + " , connectionId = " + connectionId);
        // 判断是否心跳检测，并且每次接收到消息都会更新心跳
        System.out.println("1/0 = " + 1 / 0);
        boolean isPong = webSocketManager.isPong(connectionId, message);
        if (!isPong) {
            // TODO 正常接收消息如何处理
            // webSocketManager.sendMessage(connectionId, message);
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam(CONNECTION_ID) String connectionId) {
        log.info("WebSocket closed from sessionId = {}, connectionId = {}", ((WsSession) session).getHttpSessionId(), connectionId);
        webSocketManager.disconnect(connectionId);
        // TODO 关闭连接后是否有业务处理（比如退出登陆等操作）
    }

    @OnError
    public void onError(Session session, Throwable t, @PathParam(CONNECTION_ID) String connectionId) {
        log.error("WebSocket happen error from sessionId = {}, connectionId = {}", ((WsSession) session).getHttpSessionId(), connectionId, t);
//        webSocketManager.disconnect(connectionId);
        // TODO 连接错误后是否有业务处理（比如退出登陆等操作）
    }
}
